<?php
namespace app\api\services;

use app\common\libs\Singleton;
use app\common\models\Shop\Goods;
use app\common\models\Shop\GoodsCategory;
use app\common\models\Shop\GoodsComment;
use app\common\models\Shop\GoodsOutlineDetail;
use app\common\models\Shop\GoodsParameter;
use app\common\models\Shop\GoodsSku;
use app\common\models\Shop\GoodsSpec;
use app\common\models\Shop\GoodsSpecItem;
use app\common\models\Shop\Shop;

class GoodsService
{
    use Singleton;

    public function goodsOutlineDetail($goodsId): array
    {
        $field = 'rule,content';
        $where = [
            ['goods_id', '=', $goodsId],
        ];
        $info = GoodsOutlineDetail::getInstance()->where($where)->field($field)->find();
        if (empty($info)) {
            return [];
        } else {
            $info = $info->toArray();
        }
        $info['content'] = json_decode($info['content'], true);
        return $info;
    }

    public function parameter($goodsId): array
    {
        $field = 'title,content';
        $where = [
            ['goods_id', '=', $goodsId],
        ];
        $info = GoodsParameter::getInstance()->where($where)->field($field)->select();
        if (empty($info)) {
            return [];
        }
        return $info->toArray();
    }

    public function goodsSkuListByIds($ids): array
    {
        $field = 'id,sell_price,sku_img,sku_title';
        $where = [
            ['id', 'in', $ids],
        ];
        $skuInfo = GoodsSku::getInstance()->where($where)->column($field, 'id');
        if (empty($skuInfo)) {
            return [];
        }
        return $skuInfo;
    }

    public function goodsListByIds($ids, $field = '*'): array
    {
        $where = [
            ['status', '=', 1],
            ['deleted', '=', 0],
            ['id', 'in', $ids],
        ];
        return Goods::getInstance()->where($where)->field($field)->column($field, 'id');
    }

    public function getComment($goodsId, $isImg, $isBad, $page, $pageSize)
    {
        $where = [
            ['goods_id', '=', $goodsId],
        ];
        if ( ! empty($isImg)) {
            $where[] = ['is_img', '=', 1];
        }
        if ( ! empty($isBad)) {
            $where[] = ['is_bad', '=', 1];
        }
        $goodsComment = GoodsComment::getInstance()
            ->where($where)
            ->field('all_score,content,img_content,user_id,create_at')
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->select();

        foreach ($goodsComment as &$val) {
            $user = MemberService::getInstance()->getUserInfo($val['user_id']);
            if (empty($user)) {
                unset($val);
                continue;
            }
            $user['userName']  = mb_substr($user['userName'], 0, 1) . '**';
            $val['userInfo']   = $user;
            $val['imgContent'] = explode(',', $val['imgContent']);
        }
        return $goodsComment;
    }

    public function skuInfo($goodsId, $skuId, $field = '*'): array
    {
        $where = [
            ['goods_id', '=', $goodsId],
            ['id', '=', $skuId],
            ['deleted', '=', 0],
        ];
        $sku = GoodsSku::getInstance()->where($where)->field($field)->find();
        return empty($sku) ? [] : $sku->toArray();
    }

    public function goodsSku($goodsId): array
    {
        $where = [
            ['goods_id', '=', $goodsId],
            ['deleted', '=', 0],
        ];
        $field = 'id,sell_price,cost_price,sku_img,goods_sales,goods_inventory,market_price,sku_title,spec_info';
        $sku   = GoodsSku::getInstance()->where($where)->field($field)->select();
        $sku   = empty($sku) ? [] : $sku->toArray();
        foreach ($sku as &$val) {
            $val['specArr'] = explode(';', $val['specInfo']);
            foreach ($val['specArr'] as $v) {
                $arr                     = explode('_', $v);
                $val['specIds'][$arr[0]] = $arr[1];
            }
        }
        return $sku;
    }

    public function goodsDetail($goodsId): array
    {
        $where = [
            ['id', '=', $goodsId],
            ['status', '=', 1],
        ];
        $field = [
            'id',
            'shop_id',
            'goods_title',
            'market_price',
            'sell_price',
            'cost_price',
            'goods_img',
            'goods_type',
            'goods_sales',
            'goods_inventory',
            'content',
            'is_sku',
            'rule_switch',
            'goods_inside_img',
            'is_postage',
            'sp_id',
            'gxz_rate',
            'goods_tag',
            'goods_service',
            'channel_type',
        ];
        $goodsInfo = Goods::getInstance()->where($where)->field($field)->find();
        $goodsInfo = empty($goodsInfo) ? [] : $goodsInfo->toArray();
        if ( ! empty($goodsInfo)) {
            $goodsInfo['goodsInsideImg'] = explode(',', $goodsInfo['goodsInsideImg']);
            $goodsInfo['gxz']            = $this->getGxz($goodsInfo['shopId'], $goodsInfo['gxzRate'], $goodsInfo['sellPrice']);
            $goodsInfo['goodsTag']       = empty($goodsInfo['goodsTag']) ? [] : json_decode($goodsInfo['goodsTag'], true);
            $goodsInfo['goodsService']   = empty($goodsInfo['goodsService']) ? [] : json_decode($goodsInfo['goodsService'], true);
        }
        return $goodsInfo;
    }

    public function getGxz($shopId, $goodsGxzRate, $price): string
    {
        $rate    = Shop::getInstance()->where('id', $shopId)->value('gxz_rate');
        $gxzRate = $goodsGxzRate > 0 ? $goodsGxzRate : $rate;
        return bcmul($price, bcmul($gxzRate, 0.01, 4), 4);
    }

    public function specInfo($goodsId)
    {
        $where = [
            ['goods_id', '=', $goodsId],
        ];
        $spec = GoodsSpec::getInstance()->where($where)->field('id as spec_id,title')->select();
        if (empty($spec)) {
            return [];
        }
        foreach ($spec as &$val) {
            $where = [
                ['spec_id', '=', $val['specId']],
            ];
            $item = GoodsSpecItem::getInstance()->where($where)->field('id as item_id,title')->select();
            if (empty($item)) {
                unset($val);
                continue;
            }
            $val['itemList'] = $item->toArray();
        }
        return $spec;
    }

    /**
     * @param $categoryType 1线下 2线上
     * @return array
     */
    public function goodsCategory($categoryType, $pid = 0): array
    {
        $where = [
            ['status', '=', 1],
            ['category_type', '=', $categoryType],
            ['deleted', '=', 0],
            ['shop_id', '=', 0],
        ];
        if ($pid > 0) {
            $where[] = ['pid', '=', $pid];
        }
        $category = GoodsCategory::getInstance()
            ->where($where)
            ->field('id,title')
            ->order('sort desc')
            ->select();
        return empty($category) ? [] : $category->toArray();
    }

    public function goodsInfo($shopId, $page, $pageSize, $goodsType, $sort, $keyword, $categoryId, $field = '*', $isLike = 0, $positionType = 0): array
    {
        $where = [
//            ['shop_id', '=', $shopId],
            ['status', '=', 1],
            ['goods_type', '=', $goodsType],
            ['deleted', '=', 0],
        ];
        if ( ! empty($categoryId)) {
            $where[] = ['category_id', '=', $categoryId];
        }
        if ( ! empty($shopId)) {
            $where[] = ['shop_id', '=', $shopId];
        }
        if ( ! empty($keyword)) {
            $where[] = ['goods_title', 'like', '%' . $keyword . '%'];
        }

        if ($isLike) {
            $sort = 1;
        }

        if ($positionType) {
            $where[] = ['position_type', '=', $positionType];
        }

        $arr = ['sort desc', 'goods_sales desc', 'sell_price asc', 'sell_price desc'];

        $list = Goods::getInstance()
            ->where($where)
            ->field($field)
            ->limit(($page - 1) * $pageSize, $pageSize)
            ->order($arr[$sort] ?? $arr[0])
            ->select();
        return empty($list) ? [] : $list->toArray();
    }
}
